package com.dg.river.core.util.promissions;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;

import androidx.core.content.ContextCompat;

import com.dg.river.R;
import com.dg.river.module.common.dialog.error.NormalMessageDialog;
import com.dg.river.storage.AppSettingManager;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import java.util.List;

/**
 * @author sfs
 * @description 权限管理类
 * @date 2022/11/07
 */
public class PermissionUtils {
    private final Context mContext;
    private NormalMessageDialog tipsDialog;

    private PermissionUtils(Context context) {
        this.mContext = context;
    }

    public static PermissionUtils getInstance(Context context) {
        return new PermissionUtils(context);
    }

    //region 通用权限处理方法

    private void check(String tips, String[] permissions, boolean isRefused, PermissionListener listener) {
        if (checkPermissions(permissions)) {
            //首次申请或已拒绝权限
            if (!isRefused) {
                if (tipsDialog == null) {
                    NormalMessageDialog builder = new NormalMessageDialog(mContext);
                    builder.setTitle("温馨提示");
                    builder.setMessage(tips);
                    builder.setCancelButton("取消", R.color.red_f13232, (dialog, which) -> {
                        dialog.dismiss();
                        tipsDialog = null;
                        listener.onRefuse();
                    });
                    builder.setConfirmButton("同意", R.color.red_f13232, (dialog, which) -> {
                        dialog.dismiss();
                        tipsDialog = null;
                        requestPermissions(permissions, listener);
                    });
                    tipsDialog = builder.create(R.style.dialog_message_normal_white);
                }
                tipsDialog.show();
            } else {
                listener.denied();
            }
        } else {
            //已授权权限
            listener.granted();
        }
    }

    /**
     * 请求权限
     */
    private void requestPermissions(String[] permissions, PermissionListener listener) {
        XXPermissions.with(mContext)
                .permission(permissions)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        listener.onGranted();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        listener.onDenied();
                    }
                });
    }
    //endregion

    //region 定位权限

    private final String[] PERMISSIONS_LOCATION = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    /**
     * 请求定位权限
     */
    private void requestLocation(String tips, PermissionResultListener listener) {
        AppSettingManager.setLocationPermissionHasRequest(mContext, true);
        check(tips, PERMISSIONS_LOCATION,
                AppSettingManager.isRefuseLocation(mContext), new PermissionListener() {
                    @Override
                    public void onGranted() {
                        listener.onSuccess();
//                        LocationUtils.initLocation(mContext);
                    }

                    @Override
                    public void granted() {
                        listener.onSuccess();
//                        LocationUtils.initLocation(mContext);
                    }

                    @Override
                    public void onDenied() {
                        listener.onFail();
                    }

                    @Override
                    public void denied() {
                        listener.onFail();
                    }

                    @Override
                    public void onRefuse() {
                        AppSettingManager.setRefuseLocation(mContext, true);
                        listener.onFail();
                    }
                });
    }

    //region 相机权限

    private final String[] PERMISSIONS_CAMERA = new String[]{
            Manifest.permission.CAMERA
    };

    /**
     * 请求相机权限
     */
    private void requestCamera(String tips, PermissionResultListener listener) {
        check(tips, PERMISSIONS_CAMERA,
                AppSettingManager.isRefuseCamera(mContext), new PermissionListener() {
                    @Override
                    public void onGranted() {
                        listener.onSuccess();
                    }

                    @Override
                    public void granted() {
                        listener.onSuccess();
                    }

                    @Override
                    public void onDenied() {
                        listener.onFail();
                    }

                    @Override
                    public void denied() {
                        listener.onFail();
                    }

                    @Override
                    public void onRefuse() {
                        AppSettingManager.setRefuseCamera(mContext, true);
                        listener.onFail();
                    }
                });
    }

    public void requestCameraForTrip(PermissionResultListener listener) {
        requestCamera(mContext.getString(R.string.permission_tips_camera_scan), listener);
    }

    public void requestCameraForAddShip(PermissionResultListener listener) {
        requestCameraDocument(mContext.getString(R.string.permission_add_ship_camera_scan), listener);
    }

    public void requestCameraForCommon(PermissionResultListener listener) {
        requestCameraDocument(mContext.getString(R.string.permission_pic_camera_scan), listener);
    }

    //region 相机 文件权限

    private final String[] PERMISSIONS_CAMERA_Document = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    /**
     * 请求相机 文件权限
     */
    private void requestCameraDocument(String tips, PermissionResultListener listener) {
        check(tips, PERMISSIONS_CAMERA_Document,
                AppSettingManager.isRefuseCameraDocument(mContext), new PermissionListener() {
                    @Override
                    public void onGranted() {
                        listener.onSuccess();
                    }

                    @Override
                    public void granted() {
                        listener.onSuccess();
                    }

                    @Override
                    public void onDenied() {
                        listener.onFail();
                    }

                    @Override
                    public void denied() {
                        listener.onFail();
                    }

                    @Override
                    public void onRefuse() {
                        AppSettingManager.setRefuseCameraDocument(mContext, true);
                        listener.onFail();
                    }
                });
    }

    //region 文件权限

    private final String[] PERMISSIONS_DOCUMENT = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    /**
     * 请求本地文档权限
     */
    private void requestDocument(String tips, PermissionResultListener listener) {
        check(tips, PERMISSIONS_DOCUMENT,
                AppSettingManager.isRefuseDocument(mContext), new PermissionListener() {
                    @Override
                    public void onGranted() {
                        listener.onSuccess();
                    }

                    @Override
                    public void granted() {
                        listener.onSuccess();
                    }

                    @Override
                    public void onDenied() {
                        listener.onFail();
                    }

                    @Override
                    public void denied() {
                        listener.onFail();
                    }

                    @Override
                    public void onRefuse() {
                        AppSettingManager.setRefuseDocument(mContext, true);
                        listener.onFail();
                    }
                });
    }

    public void requestDocumentForWorkmate(PermissionResultListener listener) {
        requestDocument(mContext.getString(R.string.permission_tips_document_workmate), listener);
    }

    //region 检测权限

    /**
     * 多个权限是否拒绝授权
     */
    private boolean checkPermissions(String... permissions) {
        for (String permission : permissions) {
            if (checkPermission(permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 单个权限是否拒绝授权, 只有同意返回false， 拒绝和首次请求返回true
     */
    private boolean checkPermission(String permission) {
        return ContextCompat.checkSelfPermission(mContext, permission) ==
                PackageManager.PERMISSION_DENIED;
    }
    //endregion

    public void goSetting(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示")
                .setMessage(msg)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        PermissionUtils.getInstance(mContext).toSelfSetting();
                    }
                }).setNegativeButton("取消", null);
        builder.create();
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 跳转设置界面
     */
    public void toSelfSetting() {
        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        mIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
        mContext.startActivity(mIntent);
    }

    //region 回调接口

    public interface PermissionListener {
        /**
         * 首次权限授权
         */
        void onGranted();

        /**
         * 权限已经授权
         */
        void granted();

        /**
         * 首次权限拒绝
         */
        void onDenied();

        /**
         * 权限已经拒绝
         */
        void denied();

        /**
         * 直接点击取消
         */
        void onRefuse();
    }

    public interface PermissionResultListener {
        /**
         * 成功授权
         */
        void onSuccess();

        /**
         * 未成功授权
         */
        void onFail();
    }
    //endregion
}
